import FlowHeader from '@/components/WorkFlow/flowHeader';
import personModel from '@/components/ChoisePerson/personModel';
import FlowContent from '@/components/WorkFlow/flowContent';
import {
	mapGetters
} from 'vuex'
import { functionTree, get_table_title, query_table_data } from '@/api/basedata/permissions.js'
import {
	formatTreeData
} from '@/utils/utils'
import {
	queryPage as queryDataAccessPage
} from '@/api/basedata/DataAccess.js'
import {
	queryPage as querybusinessPage
} from '@/api/basedata/business.js'
import {
	saveOrUpdate,
	getFlowsDetails
} from '@/api/basedata/permissionsApply'
import { getUserInfo } from "@/utils/auth.js";

export default {
	components: {
		FlowContent,
		FlowHeader,
		personModel,
	},
	data() {
		return {
			loading: false,
			showSendVisible: false,
			visible: false,
			UserListoption: [],
			chenckuser: [],
			receiveUserList: [],
			chenckorglist: [],
			title: '权限申请',
			billCode: '',
			billDate: '',
			describtion: '',
			personList: [],
			props: {
				children: 'children',
				label: 'name'
			},
			applyPerson: '',
			taskStatus: 0,
			rightList: [{
				text: '功能权限',
				value: 1
			}, {
				text: '数据权限',
				value: 5
			},
			{
				text: 'APP权限',
				value: 2
			}, {
				text: '微信小程序权限',
				value: 3
			}],
			rightIndex: 1,
			leftTableData: [],
			newfunctiontreeData: [],
			functiontreeData: [],
			newtree: [],
			arrA: [],
			checkA: [],
			arrC: [],
			checkC: [],
			arrD: [],
			checkD: [],
			/* 数据权限*/
			systree: [],
			sendPerson: '',
			checkarr: [],
			taskTypeText: ['发起', '已保存', '审批中', '已完成', '撤销', '不通过'],
			approvalVisible: false,
			approvalNode: [],
			processManagerId: '',
			processTaskId: '',
			tipInfo: {},
			readOnly: false,
			approveTableData: [],
			currentNodeId: '',
			tableTitle: [],
			rightDataSource: [], // 右边被选中的数据功能
			selectedTreeData: {},
			rightTableData: [],
			/** 数据权限*/
			radio: '',
			tableData: [],
			allTableData: [],
			checktableData: [],
			allNode: [],
			radio1: true,
			rightloading: false,
			loading1: false,
			searchValue: '',
			id: '',
		}
	},
	watch: {
    searchValue: {
      deep: true,
      handler() {
        this.debounce(this.changeValue, 2000)
      }
    }
  },
	mounted() {
		this.initBaseData();
		const { query } = this.$route;
    if (!query.type) { // 发起流程
      this.$refs.flowcontent.initBaseData('PermissionApply');
      this.billDate = new Date().Format('yyyy-MM-dd hh:mm:ss');
      this.applyPerson = getUserInfo().userRealName;
      return
    }
    this.initFlowsData2();
    this.readOnly = true;
	},
	methods: {
		debounce(fn, wait) {
      if (this.timer !== null) {
        clearTimeout(this.timer)
      }
      this.timer = setTimeout(fn, wait)
    },
    changeValue() {
      if (this.searchValue === '') {
        this.tableData = this.allTableData;
      } else {
        this.tableData = this.allTableData.filter(item => this.tableTitle.some(items => (item[items.columnName])?.indexOf(this.searchValue) > -1));
      }
    },
		initBaseData () {
			const params = {
				page: 1,
				pageSize: 10000
			}
			/** 获取功能树*/
			this.changetight(this.rightIndex)
			/** 获取数据权限的系统树*/
			querybusinessPage(params).then(res => {
				res.data.data.forEach(item => {
					item.children = []
					item.hierarchytyp = 'system'
				})
				this.newtree = res.data.data
				let arr = []
				queryDataAccessPage(params).then(res => {
					arr = res.data.data.map(item => {
						item.items = []
						return item
					})
					this.newtree.forEach(b => {
						for (const c in arr) {
							if (b.id == arr[c].systemId) {
								b.children.push(arr[c])
							}
						}
					})
				})
			})
		},
		handleBusiness() {
      const params = {
        process_success: {
          url: '/base/system/limits/apply/update_apply_status',
          data: {
						applyStatus: 2,
						billCode: this.billCode,
					},
          httpMethod: 'get',
        },
        process_failure: ''
      }
      this.showSendVisible = false;
      this.$refs.flowcontent.handleToFlow(params);
    },
    /**
     * @Description: 
     * @Param: 1为保存，2为最后提交/3 中间提交
     * @Author: wangwangwang
     * @param {*} type
     */
    handleFinish() {
    },
    handleSubmit(type) {
      const { query } = this.$route;
      if (query.type * 1 === 2 && type === 2 && query.taskType * 1 !== 2) {
        this.showSendVisible = true;
        return
      }
			/**
			* @Description: 发起流程
			* @param {*} 
			* @Author: wangwangwang
			*/
			if (!this.personList.length) {
				this.$message.warning('请选择要授权的人员')
				return
			}
			if (!this.arrA.length && !this.arrC.length && !this.arrD.length && !this.checktableData.length) {
				this.$message.warning('请选择功能')
				return
			}
			const userList = this.personList.map((item) => item.type===1?{foreignType: 'user', foreignId: item.id, foreignName: item.name}:{foreignType: 'station', foreignId: item.id, foreignName: item.name})
			const functionListA = this.arrA.map(item => ({
				type: '1',
				buttonId: item.id,
				buttonName: item.name,
				functionId: item.parentId
			}))
			const functionListC = this.arrC.map(item => ({
				type: '2',
				buttonId: item.id,
				buttonName: item.name,
				functionId: item.parentId
			}))
			const functionListD = this.arrD.map(item => ({
				type: '3',
				buttonId: item.id,
				buttonName: item.name,
				functionId: item.parentId
			}))
			const functionList = [...functionListA, ...functionListC, ...functionListD];
			/**
			* @Description: 设置数据权限
			* @param {*}
			* @Author: wangwangwang
			*/
			const dataJoinList = this.checktableData.map(item => {
				const dataItemList = item.tableData.map(items => ({dataId: items.ID}));
				return {systemId: item.system.systemId, dataLimitsId: item.systemId, dataLimitsName: item.systemName,tableName: item.tableTitle[0].tableName, dataItemList,field1:JSON.stringify(item.tableTitle)};
			})
			const params = {
				applyStatus: 1,
				billCode: this.billCode,
				billDate: this.billDate,
				describtion: this.describtion,
				functionList,
				dataJoinList,
				userList,
				id: this.id,
			}
			saveOrUpdate(params).then(res => {
				if (res.code === 1001) {
					const data = {
						dataSource: 'PermissionsApply',
						dataContent: '', // 业务数据
					}
					this.id = res.data.id;
					this.$refs.flowcontent.saveFlows(type, data);
				}
			})
    },
    handleFlowChat() {
      this.$refs.flowcontent.showFlowNode()
    },
    handleCancel() {
      this.showSendVisible = false;
    },
    /**
     * @Description: 回显业务数据
     * @Param: 
     * @Author: wangwangwang
     */
    initFlowsData2() {
      const { query } = this.$route;
			getFlowsDetails({ billCode: query.receiptNumber }).then(res => {
				if (res.code === 1001) {
					this.describtion = res.data.describtion;
					this.personList = res.data.userList.map(item => item.foreignType==='user'?{name: item.foreignName, id: item.foreignId, type: 1}:{name: item.foreignName, id: item.foreignId, type: 2});
					const arrA = [];
					const arrC = [];
					const arrD = [];
					for (let i = 0; i < res.data.functionList.length; i+=1) {
						const data = {
							id: res.data.functionList[i].buttonId,
							name: res.data.functionList[i].buttonName,
							parentId: res.data.functionList[i].functionId,
						}
						if (res.data.functionList[i].type === 1) {
							arrA.push(data)
						}
						if (res.data.functionList[i].type === 2) {
							arrC.push(data)
						}
						if (res.data.functionList[i].type === 3) {
							arrD.push(data)
						}
					}
					this.arrA = arrA;
					this.arrC = arrC;
					this.arrD = arrD;
					/**
					 * @Description: 回显数据权限
					 * @param {*}
					 * @Author: wangwangwang
					 */	
					const checktableData = res.data.dataJoinList.map(item => {
						const tableData = item.dataItemList.map(items => ({ID: items.dataId}));
						return {system: {systemId: item.systemId, tableName: item.tableName,id: item.dataLimitsId}, systemId: item.dataLimitsId, systemName: item.dataLimitsName,tableData,tableTitle:JSON.parse(item.field1)};
					});
					this.checktableData = checktableData;
				}
			})
      this.title = query.taskName;
      this.billCode = query.receiptNumber;
      this.billDate = query.createTime;
      this.applyPerson = query.createUserName;
      this.taskStatus = query.taskStatus;
    },
    sendCode(code) {
      this.billCode = code;
    },
		/**
		 * @description 功能权限
		 * 功能权限已选中数据*/
		getButton() {
			const keys = [...this.$refs.functiontree.getCheckedNodes(), ...this.$refs.functiontree.getHalfCheckedNodes()]
			this.newfunctiontreeData = formatTreeData(keys, 'id', 'parentId', 'children', 'parent_id')
			this.$refs.newfunctiontree.setCheckedKeys(this.$refs.functiontree.getCheckedKeys())
			this.set(keys, this.$refs.functiontree.getCheckedKeys())
		},
		/** 切换权限类型,获取功能权限*/
		changetight(num) {
			this.functiontreeData = []
			this.rightIndex = num
			if (num !== 5) {
				this.loading1 = true
				functionTree({
					type: this.rightIndex
				}).then(res => {
					const {
						data
					} = res
					this.functiontreeData = formatTreeData(data.map(item => ({...item, disabled: this.readOnly})), 'id', 'parentId', 'children', 'parent_id')
					this.get()
				})
			}
		},
		/* 获取选中的功能权限*/
		get() {
			if (this.rightIndex == 1) {
				this.newfunctiontreeData = formatTreeData(this.arrA, 'id', 'parentId', 'children', 'parent_id')
				this.$refs.newfunctiontree.setCheckedKeys(this.checkA)
				this.$refs.functiontree.setCheckedKeys(this.checkA)
			}
			if (this.rightIndex == 2) {
				this.newfunctiontreeData = formatTreeData(this.arrC, 'id', 'parentId', 'children', 'parent_id')
				this.$refs.newfunctiontree.setCheckedKeys(this.checkC)
				this.$refs.functiontree.setCheckedKeys(this.checkC)
			}
			if (this.rightIndex == 3) {
				this.newfunctiontreeData = formatTreeData(this.arrD, 'id', 'parentId', 'children', 'parent_id')
				this.$refs.newfunctiontree.setCheckedKeys(this.checkD)
				this.$refs.functiontree.setCheckedKeys(this.checkD)
			}
			this.loading1 = false
		},
		/* 设置选中的功能权限*/
		set(arr, chekarr) {
			if (this.rightIndex == 1) {
				this.arrA = arr
				this.checkA = chekarr
			}
			if (this.rightIndex == 2) {
				this.arrC = arr
				this.checkC = chekarr
			}
			if (this.rightIndex == 3) {
				this.arrD = arr
				this.checkD = chekarr
			}
		},

		/**
		 * @description 功能权限
		 *获取数据权限表*/
		async gettable(data) {
			/* 获取表头数据*/
			this.rightloading = true;
			const item = this.checktableData.find(res => (res.system == this.radio))
			if (item?.tableData) {
				this.radio1 = false
			}
			this.$refs.reftableData.clearSelection()
			this.table = data
			await get_table_title({
				dataLimitsId: data.id
			}).then(res => {
				this.tableTitle = res.data
			})
			const params = {
				page: 1,
				pageSize: 99999,
				id: this.table.id,
				systemId: this.table.systemId,
				tableName: this.table.tableName
				// foreignType: this.leftIndex,
				// foreignId: this.getforeignId(),
			}
			/* 获取表、数据*/
			await query_table_data(params).then(res => {
				this.tableData = res.data.data;
				this.allTableData = res.data.data;
			})

			this.$nextTick(() => {
				this.rightloading = false
				if (item?.tableData) {
					for (const b of item.tableData) {
						const index = this.tableData.findIndex(a => (a.ID == b.ID))
						this.radio1 = false
						this.$refs.reftableData.toggleRowSelection(this.tableData[index])
					}
				}
			})
		},
		/**
		 * @description  保存选中的数据权限
		 * @param {object} val 数据权限表的选中数据
		 * @author fxg
		 */
		changeval(val) {
			if (!this.radio1) {
				this.radio1 = true
				return
			}
			const index = this.checktableData.findIndex(res => (res.systemId == this.radio.id))
			if (val.length == 0) {
				if (index !== -1) {
					this.checktableData.splice(index, 1)
				}
				return
			}
			/**
			 * @type {object}
			 * @namespace
			 * @property  {string} arr.systemId 数据系统ID
			 * @property  {string} arr.systemName 数据系统名
			 * @property  {object} arr.system 数据系统对象
			 * @property  {Array} arr.tableTitle 选中数据权限表头
			 * @property  {Array} arr.tableData 选中数据权限集合
			*/
			var arr = {
				systemName: this.radio.name,
				tableTitle: this.tableTitle,
				tableData: val,
				system: this.radio,
				systemId: this.radio.id
			}
			if (index == -1) {
				this.checktableData.push(arr)
			} else {
				this.checktableData.splice(index, 1, arr)
			}
		},
		addUserlist() {
			this.visible = true;
		},
		delUserList(index) {
			this.personList.splice(index, 1);
		},
		closeModel() {
      this.visible = false;
    },
		getPerson(data) {
      this.visible = false;
			this.personList = data;
    },
	},
	computed: {
		...mapGetters({
			screenWidth: 'getscreenWidth',
			screenHeight: 'getscreenHeight',
			Collapse: 'getsCollapse'
		}),
		style() {
			let num = 0
			if (this.Collapse) {
				num = this.screenWidth - 124
			} else {
				num = this.screenWidth - 220
			}
			return 'width:' + num + 'px;'
		}
	}
}
